#!/usr/bin/bash
version=6.0.10
installDir=/data/redis
srcDir=/data/downloads
user=redis
Red='\033[1;31m'
Green='\033[1;32m'
Yellow='\033[1;33m'
Blue='\033[1;34m'
Purple='\033[1;35m'
Cyan='\033[1;36m'
While='\033[1;37m'
Reset='\033[0m'
echo -e "${Red}该脚本是数商云安装部署redis单机点版本, redis版本为: ${version}, 安装目录为: ${installDir}${Reset}"
echo -e "${Yellow}确定要初始化请按回车，否则ctrl+c终止脚本。${Reset}"
read -p "" xxxx

function checkDistro() {
  for i in issue os-release issue.net centos-release redhat-rekease;do
    if [[ -f /etc/$i ]];then
      if grep -q "$1" /etc/$i;then
        return 0
      fi
    fi
  done
  return 1
}

function installNewGcc() {
if checkDistro 'CentOS';then
echo '
# CentOS-SCLo-sclo.repo
#
# Please see http://wiki.centos.org/SpecialInterestGroup/SCLo for more
# information

[centos-sclo-sclo]
name=CentOS-7 - SCLo sclo
baseurl=http://mirrors.aliyun.com/centos/7/sclo/$basearch/sclo/
# mirrorlist=http://mirrorlist.centos.org?arch=$basearch&release=7&repo=sclo-sclo
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-sclo-testing]
name=CentOS-7 - SCLo sclo Testing
baseurl=http://mirrors.aliyun.com/centos/7/sclo/$basearch/sclo/
gpgcheck=0
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-sclo-source]
name=CentOS-7 - SCLo sclo Sources
baseurl=http://mirrors.aliyun.com/centos/7/sclo/Source/sclo/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-sclo-debuginfo]
name=CentOS-7 - SCLo sclo Debuginfo
baseurl=http://mirrors.aliyun.com/centos/7/sclo/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo' > /etc/yum.repos.d/CentOS-SCLo-scl.repo

echo '# CentOS-SCLo-rh.repo
#
# Please see http://wiki.centos.org/SpecialInterestGroup/SCLo for more
# information

[centos-sclo-rh]
name=CentOS-7 - SCLo rh
baseurl=http://mirrors.aliyun.com/centos/7/sclo/$basearch/rh/
#mirrorlist=http://mirrorlist.centos.org?arch=$basearch&release=7&repo=sclo-rh
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-rh-testing]
name=CentOS-7 - SCLo rh Testing
baseurl=http://mirrors.aliyun.com/centos/7/sclo/$basearch/rh/
gpgcheck=0
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-rh-source]
name=CentOS-7 - SCLo rh Sources
baseurl=http://mirrors.aliyun.com/centos/7/sclo/Source/rh/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo

[centos-sclo-rh-debuginfo]
name=CentOS-7 - SCLo rh Debuginfo
baseurl=http://mirrors.aliyun.com/centos/7/sclo/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-SIG-SCLo' >  /etc/yum.repos.d/CentOS-SCLo-scl-rh.repo

yum install -y devtoolset-11-gcc devtoolset-11-gcc-c++ devtoolset-11-binutils
source /opt/rh/devtoolset-11/enable
elif checkDistro 'Ubuntu';then
    echo "还没做"
fi
}

function installTools() {
  if checkDistro 'CentOS';then
    yum install -y jemalloc-devel centos-release-scl gcc
  elif checkDistro 'Ubuntu';then
    apt update
    apt install -y wget curl gcc make libjemalloc-dev
  fi
}

function versionCheckGcc() {
  gccVersion=$(gcc --version | head -n1 | cut -d " " -f3 | cut -d "." -f1)
  if [[ ${gccVersion} == "4" ]] || [[ ${gccVersion} == "5" ]];then
    installNewGcc
  fi
}

function createUser() {
    if id ${user} &> /dev/null ;then
      echo "${user} 用户已存在"
    else
      useradd -r -s /sbin/nologin redis
      echo "${user} 用户创建成功"
    fi
}

function downloadAndUnzip() {
  mkdir -p ${srcDir}
  cd ${srcDir}
  wget http://download.redis.io/releases/redis-${version}.tar.gz
  tar xf redis-${version}.tar.gz
}

function installRedis() {
  cd redis-${version}
  make PREFIX=${installDir} install
  if [ -f ${installDir}/bin/redis-server ];then
    echo "redis 安装成功"
  else
    echo "redis 安装失败"
  fi
}

function configSetup() {
  ln -s ${installDir}/bin/redis-* /usr/bin/
  mkdir -p ${installDir}/{etc,log,data,run}
  cp redis.conf ${installDir}/etc/ && action "成功复制redis.conf文件"
  #sed -i -e 's/bind 127.0.0.1/bind 0.0.0.0/' -e "/# requirepass/a requirepass $PASSWORD" -e "/^dir .*/c dir ${INSTALL_DIR}/data/" -e "/logfile .*/c logfile ${INSTALL_DIR}/log/redis-6379.log" -e "/^pidfile .*/c pidfile ${INSTALL_DIR}/run/redis_6379.pid" ${INSTALL_DIR}/etc/redis.conf
  sed -i -e 's/bind 127.0.0.1/bind 0.0.0.0/' -e "/^dir .*/c dir ${installDir}/data/" -e "/logfile .*/c logfile ${installDir}/log/redis-6379.log" -e "/^pidfile .*/c pidfile ${installDir}/run/redis_6379.pid" ${installDir}/etc/redis.conf

  overcommitHead=$(grep vm.overcommit_memory /etc/sysctl.conf | grep -o '#')
  if [[ ${overcommitHead} == '#' ]];then
    echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
  else
    overcommitValue=$(grep vm.overcommit_memory /etc/sysctl.conf | awk '{print $NF}')

    if [[ ${overcommitValue} == "" ]];then
      echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
    elif [[ ${overcommitValue} == "0" ]];then
      sed -i 's#vm.overcommit_memory = 0#vm.overcommit_memory = 1#' /etc/sysctl.conf
    fi
  fi

  somaxHead=$(grep net.core.somaxconn /etc/sysctl.conf | grep -o '#')
  if [[ ${somaxHead} == '#' ]];then
    echo 'net.core.somaxconn = 32768' >> /etc/sysctl.conf
  else
    somaxValue=$(grep net.core.somaxconn /etc/sysctl.conf | awk '{print $NF}')

    if [[ ${somaxValue} == "" ]];then
      echo 'net.core.somaxconn = 32768' >> /etc/sysctl.conf
    elif [[ ${somaxValue} < "1024" ]];then
      sed -i 's#net.core.somaxconn = '"${somaxValue}"'#net.core.somaxconn = 32768#' /etc/sysctl.conf
    fi
  fi

  sysctl -p

  echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local
  chmod +x /etc/rc.d/rc.local
  /etc/rc.d/rc.local
}

function changeUser() {
  chown -R ${user}: ${installDir}
}

function makeService() {
if CheckDistro 'CentOS';then
cat > /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=${installDir}/bin/redis-server ${installDir}/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT \$MAINPID
#Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
elif CheckDistro 'Ubuntu';then
cat > /lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=/apps/redis/bin/redis-server /apps/redis/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT \$MAINPID
#Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
fi
}

function startRedis() {
  systemctl daemon-reload
  systemctl enable --now redis.service &> /dev/null
  if [ ! -z "$(ps -ef | grep redis | grep -v grep)" ]; then
      echo "redis install success"
  else
      echo "redis install fail"
  fi
}

function main() {
  installTools
  versionCheckGcc
  createUser
  downloadAndUnzip
  installRedis
  configSetup
  changeUser
  makeService
  startRedis
  startRedis
}

main
